#include "ModalFilter.h"
#include "ModalFilterSystem.h"
#include "AudioInterface.h"
#include <math.h>
#include <assert.h>
#include <iostream>

SinSweepFilter::SinSweepFilter(float startFreq, float endFreq, float maxDuration)
{
	m_numSamples = (int)(((float)SAMPLE_RATE * maxDuration));
	m_freqIncrement = (endFreq - startFreq) / m_numSamples;
	m_startFreq = startFreq; 
	m_endFreq = endFreq;
}

float SinSweepFilter::Process(int sampleNum, float energy, ModalFilterSystem* system)
{
	if (sampleNum >= m_numSamples)
	{
		return 0;
	}
	else
	{
		float amplitudeScaler = 3; 
		//Frequency sweep
		float frequency = m_startFreq + (sampleNum * m_freqIncrement); // * energy
		frequency *= energy/80;
		float sample = amplitudeScaler * (float)(sin(TWO_PI * frequency * sampleNum / SAMPLE_RATE ));

		

		// y = mx + b
		// m
		// 1 = m * 0 + 400
		
		// m = y - b / x
		


		return sample;
	}
}


DecayingSinFilter::DecayingSinFilter(float frequency,float maxDuration)
{
	m_frequency = frequency;
	m_numSamples = (int)(maxDuration * SAMPLE_RATE);
}

float DecayingSinFilter::Process(int sampleNum, float energy, ModalFilterSystem* system)
{

	float freq = m_frequency * (energy/ 50);
	float amplitudeScaler = 3;
	
	float sample = amplitudeScaler * (float)(sin(TWO_PI * freq * sampleNum / SAMPLE_RATE ));

	
	float duration = system->FrequencyDurationEnvelope(freq);

	float m = -1 / duration;
	float b = 1;

	float env = duration*m;
	env += b;
	env *= env * amplitudeScaler;
	
	
	if(sample > 0 && sample > env)
	{
		sample = env;
	}
	else if(sample < 0 && sample < -env)
	{
		sample = -env;
	}
	

	return sample;
}